import 'dart:io';
import 'dart:ui';
import 'dart:isolate';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

class CheckUpdate {
  static String _downloadPath = '';
  static String _filename = 'YOUR_APP.apk';
  static String _taskId = '';

  upload() async {
    print('更新开始');
    // 判断系统，ios跳转app store，安卓下载新的apk
    if (Platform.isIOS) {
      // 跳转app store
    } else if (Platform.isAndroid) {
      await _prepareDownload();
      if (_downloadPath.isNotEmpty) {
        await FlutterDownloader.cancelAll();
        await download();
      }
    }
  }

  // 下载前的准备
  static Future<void> _prepareDownload() async {
    print('创建本地文件储存路径');
    _downloadPath = (await _findLocalPath()) + '/Download';
    final savedDir = Directory(_downloadPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
    print('--------------------downloadPath: $_downloadPath');
  }

  // 获取下载地址
  static Future<String> _findLocalPath() async {
    print('获取本地文件储存路径');
    final directory = Platform.isAndroid
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory.path;
  }

  // 检查权限
  static Future<bool> _checkPermission() async {
    print('检查权限');
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  // 下载完成之后的回调
  static downloadCallback(id, status, progress) {
    print('下载完成回调');
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  // 下载apk
  static Future<void> download() async {
    final bool _permissionReady = await _checkPermission();
    if (_permissionReady) {
      print('下载apk');
      ReceivePort _port = ReceivePort();
      _taskId = await FlutterDownloader.enqueue(
        url: 'http://139.196.123.227:8111/uploads/app-v0.0.1.apk',
        savedDir: _downloadPath,
        // fileName: _filename,
        showNotification: true,
        openFileFromNotification: true,
      );
      FlutterDownloader.registerCallback(downloadCallback);

      IsolateNameServer.registerPortWithName(
          _port.sendPort, 'downloader_send_port');

      _port.listen((dynamic data) async {
        print('监听');
        String id = data[0];
        DownloadTaskStatus status = data[1];
        int progress = data[2];
        print(data);
        print(id);
        print(status);
        print(progress);
        if (status == DownloadTaskStatus.complete) {
          print('安装');
          // 更新弹窗提示，确认后进行安装
          OpenFile.open('$_downloadPath/$_filename');
          print(
              '==============_installApkz: $_taskId  $_downloadPath /$_filename');
        }
      });
    } else {
      print('-----------------未授权');
    }
  }

  // 安装apk
  static Future<void> installApk() async {
    await OpenFile.open('$_downloadPath/$_filename');
  }
}
